<?php


namespace app\xiangji\services;


use app\common\facades\auth\Auth;
use app\common\helpers\Response;
use app\Request;
use app\xiangji\exception\BadRequestException;
use app\xiangji\exception\ServiceUnavailableException;
use app\xiangji\exception\UnauthorizedException;
use think\Exception;
use think\facade\Db;

class UserWalletService
{
    private $user;

    public function __construct()
    {
        $this->user = Auth::guard('api')->user();
    }

    /**
     * @todo 用户钱包数据
     * @return mixed
     */
    public function getUserWalletInfo()
    {
        return $this->user->wallet->hidden(['id', 'user_id', 'create_time', 'delete_time', 'update_time']);
    }

    /**
     * @todo 用户钱包日志数据
     * @param Request $request  分页数据
     * @return mixed
     */
    public function getUserWalletLogs(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        return $this->user->walletLogs()
            ->field(['id', 'change', 'scene', 'create_time'])
            ->order('id', 'desc')
            ->paginate(['list_rows' => $limit, 'page' => $page]);
    }

    /**
     * @todo 用户提现列表
     * @param Request $request
     * @return mixed
     */
    public function userWithdrawList(Request $request)
    {
        $page = $request->get('page', 1);
        $limit = $request->get('limit', 10);
        return $this->user->withdraw()
            ->order('id', 'desc')
            ->field(['id', 'trade_no', 'amount', 'status', 'fail_reason', 'create_time', 'audit_time', 'payment_time'])
            ->paginate(['list_rows' => $limit, 'page' => $page]);
    }

    // 最后一条提现状态
    public function lastWithdrawStatus()
    {
        return $this->user->withdraw()->order('id', 'desc')->field(['id', 'trade_no', 'amount', 'status', 'fail_reason', 'create_time', 'audit_time', 'payment_time'])->find();
    }

    /**
     * @todo 微信提现：需后台审核
     * @param int $amount
     * @return bool
     * @throws Exception
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function userWithdraw($amount)
    {
        if (!in_array((int)$amount, [30, 100, 500, 1000, 5000, 10000])){
            throw new BadRequestException('提现金额错误');
        }
        // 提现必须绑定手机号
        if (!$this->user->mobile){
            throw new BadRequestException('请先绑定手机号', Response::HTTP_FORBIDDEN);
        }
        // 用户钱包余额判断
        if ($this->user->wallet->balance < $amount){
            throw new BadRequestException('钱包余额不足');
        }
        $last_withdraw = $this->user->withdraw()->order('id', 'desc')->find();
        if ($last_withdraw && $last_withdraw->status == 1){
            throw new UnauthorizedException('当前还有一笔提现在处理中', Response::HTTP_FORBIDDEN);
        }
        // 校验钱包安全性
        if (!WalletService::checkWalletSecurity($this->user->wallet)){
            throw new UnauthorizedException('钱包账户异常', Response::HTTP_FORBIDDEN);
        }
        Db::startTrans();
        try {
            // 生成对应钱包日志
            WalletService::createWalletLog($this->user->wallet, 0 - $amount, '用户提现');
            // 扣除用户钱包相对应的金额
            WalletService::updateWallet($this->user->wallet, 0 - $amount);
            // 生成提现订单
            $this->user->withdraw()->save([
                'user_id'   => $this->user->id,
                'openid'    => $this->user->openId,
                'status'    => 1,
                'amount'    => $amount
            ]);
            Db::commit();
        } catch (\Exception $exception){
            throw new ServiceUnavailableException('系统错误，请稍后再试');
            Db::rollback();
        }
        return true;
    }
}
